package com.example.demo.interceptor;

import com.example.demo.annotation.Limit;
import com.example.demo.annotation.NoRepeatSubmit;
import com.example.demo.exception.RepeatSubmitException;
import com.example.demo.lock.RedisLock;
import com.example.demo.utils.HttpContextUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;

import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.UUID;

/**
 * @author lyc
 * @date 2019/6/12.
 */
public class RepeatSubmitHandler {

    private static final Logger LOGGER = LoggerFactory.getLogger(RepeatSubmitHandler.class);

    @Autowired
    private RedisLock redisLock;

    @Around("@annotation(com.example.demo.annotation.NoRepeatSubmit)")
    public Object around(ProceedingJoinPoint pjp) throws Throwable {
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        Method method = signature.getMethod();
        NoRepeatSubmit noRepeatSubmit = method.getAnnotation(NoRepeatSubmit.class);
        int lockSeconds = noRepeatSubmit.lockTime();

        HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
        Assert.notNull(request, "request can not null");

        // 此处可以用token或者JSessionId 还可以考虑 ip+请求参数+User-Agent 合起来md5
        String token = request.getHeader("Authorization");
        String path = request.getServletPath();
        String key = getKey(token, path);
        String clientId = getClientId();

        boolean isSuccess = redisLock.tryLock(key, clientId, lockSeconds);
        LOGGER.info("tryLock key = [{}], clientId = [{}]", key, clientId);

        if (isSuccess) {
            LOGGER.info("tryLock success, key = [{}], clientId = [{}]", key, clientId);
            // 获取锁成功
            Object result;

            try {
                // 执行进程
                result = pjp.proceed();
            } finally {
                // 解锁
                redisLock.releaseLock(key, clientId);
                LOGGER.info("releaseLock success, key = [{}], clientId = [{}]", key, clientId);
            }

            return result;

        } else {
            // 获取锁失败，认为是重复提交的请求
            LOGGER.info("tryLock fail, key = [{}]", key);
           return new RepeatSubmitException("重复请求，请稍后再试");
        }

    }

    private String getKey(String token, String path) {
        return token + path;
    }

    private String getClientId() {
        return UUID.randomUUID().toString();
    }
}